package com.wuyb.config.security;

import com.wuyb.enums.ErrorCode;
import com.wuyb.exception.NormalException;
import com.wuyb.util.JwtTokenUtil;
import com.wuyb.util.MyUtil;
import com.wuyb.util.RedisUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;

/**
 * 为token执行登录的过滤器
 *
 * @Author: wyb
 * @Date: 2024/01/08/19:34
 * @Description:
 */
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private RedisUtil redisUtil;

    @Resource(name = "handlerExceptionResolver")
    private HandlerExceptionResolver handlerExceptionResolver;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = request.getHeader(tokenHeader);

        if (authHeader != null && authHeader.startsWith(tokenHead)) {
            String authToken = authHeader.substring(tokenHead.length()).strip();
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            // Token存在但是没有登录
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 查询数据库获取用户信息
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                // 验证Token是否有效， 重新设置用户对象
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

                    // 如果当前ID对应Token不相等，则说明已经有人在线上了
                    Integer userId = MyUtil.getUser().getId();
                    String redisToken = redisUtil.getUserOnline(userId);
                    // 当RedisToken 为null的时候，则代表当前用户没人在线，可以直接登录
                    if (redisToken != null && !authToken.equals(redisToken)) {
                        handlerExceptionResolver.resolveException(request,response,null,new NormalException(ErrorCode.OPERATION_ERROR.getCode(), "该用户已经在其他地方登录了"));
                        return ;
                    }
                    redisUtil.putUserOnline(userId, authToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
